from flask import render_template, current_app, session, jsonify, request, g
from info import constants
from info.common import user_login_data
from info.models import News, Category
from info.utils.response_code import RET
from . import index_blu


@index_blu.route('/')
@user_login_data
def index():
    """
    :return:
    """
    user = g.user
    # 点击排行(获取数据库中的十条数据,以点击量排行)
    user_click = list()
    news_list = None
    try:
        # 若查询错误，会报错,保证用户能读到数据，设置默认值
        news_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as f:
        print(f)
    for news in news_list if news_list else []:
        user_click.append(news.to_dict())
    """
    新闻分类:
    1.从数据库中获取新闻分页列表(默认1)
    3返还响应
    """
    #  1.从数据库中获取新闻分页列表(默认1)
    category = Category.query.all()
    category_list = list()
    for category_news in category:
        category_list.append(category_news.to_dict())
    data = {
        "user":user.to_dict() if user else None,
        "user_click":user_click,
        "category_list":category_list
    }
    return render_template('news/index.html',
                           data=data)


@index_blu.route('/favicon.ico')
def favicon():
    return current_app.send_static_file('news/favicon.ico')


@index_blu.route('/news_list')
def get_news_list():
    """
    1.获取参数(第几页，多少数据，哪一列)
    2.校验参数(格式是否正确)
    3.数据库中取值(做判断)
    4.返回数据
    :return:
    """
    # 1.获取参数(第几页，多少数据，哪一列)
    args_dict = request.args
    cid = args_dict.get('cid', '1')
    page = args_dict.get('page', '1')
    per_page = args_dict.get('per_page', '10')
    # 2.检验参数(格式是否正确)
    try:
        cid = int(cid)
        page = int(page)
        per_page = int(per_page)
    except Exception as f:
        print(f)
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    # 3.从数据库中取值做判断
    filters = [News.status == 0]
    if cid != 1:
        filters.append(News.category_id == cid)
    try:
        select_news = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page, per_page, False)
        print(News.query.filter(*filters).all())
        current_page = select_news.page
        current_pages = select_news.pages
        select_items = select_news.items
    except Exception as f:
        print(f)
        return jsonify(errno=RET.DBERR, errmsg='数据库查询错误')
    news_li = list()
    for item in select_items:
        news_li.append(item.to_dict())
    data = {
        "news_li" : news_li,
        "current_page" : current_page,
        "current_pages" : current_pages
        }
    return jsonify(errno=RET.OK, errmsg='成功', data=data)
